﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.LiveFX.Client;
using Microsoft.LiveFX.ResourceModel;
using System.IO;

namespace LiveFrameworkExplorer.Plugins.VSSettings
{
    public partial class ucImportExportVSSettings : UserControl
    {
        private ILFEBase _lfeBase = null;
        private LiveOperatingEnvironment _liveFx = null;
        private MeshObject vssettings = null;
        private DataFeed vssettingsFeed = null;

        public ucImportExportVSSettings()
        {
            InitializeComponent();
        }

        private void SetUI(bool enable)
        {
            btExport.Enabled = btImport.Enabled = lbVSSettings.Enabled = btRemove.Enabled = enable;
        }

        private void FillVSSettings()
        {
            lbVSSettings.Items.Clear();
            foreach (var vsSetting in vssettingsFeed.DataEntries.Entries)
            {
                lbVSSettings.Items.Add(vsSetting);
            }
        }

        public void Init(ILFEBase lfeBase)
        {
            SetUI(false);
            _lfeBase = lfeBase;
            _liveFx = _lfeBase.GetLiveOperatingEnvironment();
            // Get the settings MeshObject
            vssettings = (from mo in _liveFx.Mesh.CreateQuery<MeshObject>()
                             where mo.Resource.Title == "VSSettings" && mo.Resource.Type == "VSSettingsFolder"
                             select mo).FirstOrDefault();
            if (vssettings == null)
            {
                vssettings = new MeshObject(new MeshObjectResource("VSSettings") { Type = "VSSettingsFolder" });
                _liveFx.Mesh.MeshObjects.Add(ref vssettings);
            }
            // Get the settings feed
            vssettingsFeed = (from feed in vssettings.CreateQuery<DataFeed>()
                              where feed.Resource.Title == "VSSettingsFiles" && feed.Resource.Type == "VSSettingsFiles"
                              select feed).FirstOrDefault();
            if (vssettingsFeed == null)
            {
                vssettingsFeed = new DataFeed(new DataFeedResource("VSSettingsFiles") { Type = "VSSettingsFiles" });
                vssettings.DataFeeds.Add(ref vssettingsFeed);                
            }
            // Display the VS Settings files
            FillVSSettings();
            SetUI(true);
        }

        private void btExport_Click(object sender, EventArgs e)
        {
            SetUI(false);
            _lfeBase.GetDTEEnvironment().StatusBar.Text = "Exporting VS Settings...";
            var tmpFile = Path.GetTempFileName();
            _lfeBase.GetDTEEnvironment().ExecuteCommand("Tools.ImportandExportSettings",
                "-export:\"" + tmpFile + "\"");
            var fileName = DateTime.Now.ToString("yyyy-MM-dd-HH-mm") + " on " + Environment.MachineName.ToUpper() + ".vssettings";
            var dlgName = new InputBox("VS Settings filename",
                "Enter the name of the current settings file") { Value = fileName };
            if (dlgName.ShowDialog() == DialogResult.OK)
            {
                _lfeBase.GetDTEEnvironment().StatusBar.Text = "Uploading VS Settings...";
                var fileStream = File.Open(tmpFile, FileMode.Open);
                DataEntry file = new DataEntry(new DataEntryResource(dlgName.Value) { Type = "LiveMeshFile" });
                vssettingsFeed.DataEntries.Add(ref file);
                file.UpdateCompleted += (object UpdateCompletedSender, AsyncCompletedEventArgs UpdateCompletedEventArgs) =>
                {
                    if (UpdateCompletedEventArgs.Error == null)
                    {
                        file.Update();
                        // Display the VS Settings files
                        FillVSSettings();
                        MessageBox.Show("VS Settings has been saved !");
                        _lfeBase.GetDTEEnvironment().StatusBar.Clear();
                    }
                    else
                        MessageBox.Show("Unable to add the VS Settings in Mesh: " + UpdateCompletedEventArgs.Error.ToString());
                    SetUI(true);
                };
                file.UpdateMediaResourceAsync(fileStream, new FileInfo(tmpFile).GetMimeType(), null);
            }
            else
                SetUI(true);
        }

        private void btImport_Click(object sender, EventArgs e)
        {
            if (lbVSSettings.SelectedItem != null)
            {
                var fileSelected = lbVSSettings.SelectedItem as DataEntry;
                if (MessageBox.Show("Are you sure to import the settings file " + fileSelected.Resource.Title + "?",
                    "Live Framework Explorer", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    _lfeBase.GetDTEEnvironment().StatusBar.Text = "Downloading " + fileSelected.Resource.Title + "...";
                    SetUI(false);
                    var tmpFile = Path.GetTempFileName();
                    var stream = File.Create(tmpFile);
                    fileSelected.ReadMediaResourceCompleted += (object RMRsender, MediaResourceAsyncEventArgs RMRe) =>
                    {
                        if (RMRe.Error == null)
                        {
                            RMRe.Result.Flush();
                            RMRe.Result.Close();
                            _lfeBase.GetDTEEnvironment().StatusBar.Text = "Importing " + fileSelected.Resource.Title + "...";                  
                            _lfeBase.GetDTEEnvironment().ExecuteCommand("Tools.ImportandExportSettings",
                                "-import:\"" + tmpFile + "\"");
                            MessageBox.Show(RMRe.UserState as String + " was successfull imported !", "Live Framework Explorer",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
                            _lfeBase.GetDTEEnvironment().StatusBar.Clear();
                        }
                        else
                        {
                            MessageBox.Show("Error to get the file: " + RMRe.Error.ToString());
                        }
                        SetUI(true);
                    };
                    fileSelected.ReadMediaResourceAsync(stream, fileSelected.Resource.Title);
                }
            }
            else
                MessageBox.Show("Please select a VS Settings file to Import");
        }

        private void btRemove_Click(object sender, EventArgs e)
        {
            if (lbVSSettings.SelectedItem != null)
            {
                var fileSelected = lbVSSettings.SelectedItem as DataEntry;
                if (MessageBox.Show("Are you sure to remove the settings file " + fileSelected.Resource.Title + "?",
                    "Live Framework Explorer", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    SetUI(false);
                    _lfeBase.GetDTEEnvironment().StatusBar.Text = "Removing " + fileSelected.Resource.Title + "...";
                    vssettingsFeed.DataEntries.Remove(fileSelected);
                    vssettingsFeed.Update();
                    FillVSSettings();
                    SetUI(true);
                    _lfeBase.GetDTEEnvironment().StatusBar.Clear();
                }
            }
            else
                MessageBox.Show("Please select a VS Settings file to remove");

        }
    }
}
